package com.example.myweb.Controller.Auth;

import com.example.myweb.Common.ApiResponse;
import com.example.myweb.Dto.FeedItemDTO;
import com.example.myweb.Dto.TopicDTO;
import com.example.myweb.Service.Auth.TopicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/topics")
public class TopicController {

    @Autowired
    private TopicService topicService;

    /**
     * 获取热门话题列表
     */
    @GetMapping("/hot")
    public ResponseEntity<ApiResponse<List<TopicDTO>>> getHotTopics(
            @RequestParam(defaultValue = "10") int limit) {
        List<TopicDTO> hotTopics = topicService.getHotTopics(limit);
        return ResponseEntity.ok(ApiResponse.success(hotTopics, "获取热门话题成功"));
    }

    /**
     * 获取指定话题下的内容流
     */
    @GetMapping("/{topicName}/content")
    public ResponseEntity<ApiResponse<Page<FeedItemDTO>>> getContentByTopic(
            @PathVariable String topicName,
            Pageable pageable) {
        Page<FeedItemDTO> contentPage = topicService.getContentByTopicName(topicName, pageable);
        return ResponseEntity.ok(ApiResponse.success(contentPage, "获取话题内容成功"));
    }

    /**
     * 搜索话题（用于自动完成）
     * GET /topics/search?q=...
     */
    @GetMapping("/search")
    public ResponseEntity<ApiResponse<List<TopicDTO>>> searchTopics(
            @RequestParam("q") String keyword,
            @RequestParam(defaultValue = "10") int limit) {

        // 防止恶意请求过大的limit
        if (limit > 50) {
            limit = 50;
        }

        List<TopicDTO> results = topicService.searchTopics(keyword, limit);
        return ResponseEntity.ok(ApiResponse.success(results, "话题搜索成功"));
    }
}